package com.uziot.bucket.shiro.config.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uziot.bucket.shiro.config.JWTToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author shidt
 * @version V1.0
 * @className AuthenticationTokenFilter
 * @date 2020-11-16 23:48:56
 * @description Shiro认证授权服务过滤器，主要负责请求进来时，
 * 获取请求头中的token信息，实现认证和权限校验
 */
@Slf4j
public class AuthenticationTokenFilter extends BasicHttpAuthenticationFilter {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();


    /**
     * 检测Header里Authorization字段
     * 判断是否登录
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader("username");
        return authorization != null;
    }

    /**
     * 登录验证
     *
     * @param request  请求
     * @param response 相应
     * @return boolan
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String bearerToken = httpServletRequest.getHeader("username");

        JWTToken token = new JWTToken(bearerToken);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        this.getSubject(request, response).login(token);
        return true;
    }


    /**
     * 是否允许访问,token合法性校验
     *
     * @param req         请求
     * @param response    相应
     * @param mappedValue 参数
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest req, ServletResponse response, Object mappedValue) {
        HttpServletRequest request = (HttpServletRequest) req;

        if (isLoginAttempt(request, response)) {
            try {
                this.executeLogin(request, response);
                return true;
            } catch (Exception e) {
                String msg = e.getMessage();
                this.response401(response, msg);
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 重写 onAccessDenied 方法，避免父类中调用再次executeLogin
     *
     * @param request  请求
     * @param response 相应
     * @return boolean
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        log.info("调用onAccessDenied拒绝访问");
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {
            JSONObject result = new JSONObject();

            result.put("data", false);
            result.put("code", "401");
            result.put("msg", "未授权的访问！");
            out.append(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error("返回Response信息出现IOException异常:" + e.getMessage());
        }
        return false;
    }

    /**
     * 401非法请求
     *
     * @param resp 响应
     * @param msg  提示信息
     */
    private void response401(ServletResponse resp, String msg) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {

            JSONObject result = new JSONObject();

            result.put("data", false);
            result.put("code", "403");
            result.put("msg", "授权访问失败！");
            out.append(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error("返回Response信息出现IOException异常:" + e.getMessage());
        }
    }
}
